package api

import (
	"log"
	"mime/multipart"

	"github.com/gin-gonic/gin"
)

type UploadResult struct {
	Message string
	Name    string
	Size    int
}

func FileUploader(path string, dst string, callback func(result *UploadResult, ctx *gin.Context), engine *gin.Engine) {
	if path == "" {
		log.Fatal("path is invalid")
		return
	}
	if dst == "" {
		log.Fatal("dst is invalid")
		return
	}
	if callback == nil {
		log.Fatal("callback is nil")
		return
	}
	if engine == nil {
		log.Fatal("engine is nil")
		return
	}
	engine.MaxMultipartMemory = 8 << 20
	engine.POST(path, func(ctx *gin.Context) {
		file, error := ctx.FormFile("file")
		if error != nil {
			callback(_getResultMessage(false, file), ctx)
			return
		}
		dstValue := dst + "/" + file.Filename
		log.Println("save the upload file to dst:", dstValue)
		error = ctx.SaveUploadedFile(file, dstValue)
		if error != nil {
			callback(_getResultMessage(false, file), ctx)
			return
		}
		callback(_getResultMessage(true, file), ctx)
	})
}

func _getResultMessage(success bool, f *multipart.FileHeader) *UploadResult {
	if success {
		return &UploadResult{
			Message: "success",
			Name:    f.Filename,
			Size:    int(f.Size),
		}
	} else {
		return &UploadResult{
			Message: "error",
			Name:    f.Filename,
			Size:    0,
		}
	}
}
